package ecustom.clients.k3client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import ecustom.clients.k3client.entities.ERPPPayableResult;
import ecustom.clients.k3client.entities.ERPPPayableResult.PayableErrors;
import ecustom.clients.k3client.entities.ERPPPayableResult.SuccessEntitys;
import ecustom.clients.k3client.entities.ERPResponseResult;
import ecustom.clients.k3client.entities.ERPResponseResult.Errors;
import ecustom.clients.servlets.HttpRequestUtil;
import ecustom.clients.util.JsonUtil;
import ecustom.common.servicelog.bean.ServiceLogBean;
import ecustom.common.util.CustomUtil;
import ecustom.common.util.PropUtil;

/**
* @author 作者:Gcc
* @createDate 创建时间：Aug 14, 2023 11:39:24 PM
*/
public class K3WebApiClient {
	
	private static final Logger log = Logger.getLogger(K3WebApiClient.class);
	
	/**
	 * 
	 * 登录信息
	 * @return
	 * @throws Exception
	 */
	public static List<String> k3Login() throws Exception {
		String url = PropUtil.getString("k3.login.url");
		String dbId = PropUtil.getString("k3.dbId.val");
		String uid = PropUtil.getString("k3.UserName.val");
		String pwd = PropUtil.getString("k3.Pwd.val");
		Object[] objs = new Object[] {dbId, uid, pwd, 2052};
		Map<String, Object> inputMap = new HashMap<String, Object>();
		inputMap.put("format", 1);
		inputMap.put("useragent", "ApiClient");
		inputMap.put("parameters", objs);
		log.info("inputJson:"+JsonUtil.toJson(inputMap));
		Map<String, Object> resuleMap = HttpRequestUtil.postJson(url, inputMap);
		
		JSONObject obj = new JSONObject().parseObject(resuleMap.get("resule")+"");
		boolean bl = obj.getBoolean("IsSuccessByAPI");
		if(!bl) {
			throw new RuntimeException("金蝶系统登录接口返回错误信息："+obj.getString("Message"));
		}
		
		List<String> cookies = (List<String>) resuleMap.get("Cookie");
		log.info("listCookie:"+JsonUtil.toJson(cookies));
		return cookies;
	}
	

	/**
	 * 保存单据接口
	 * 付款单和应付单
	 * @param dataJson 采购DataJson数据
	 * @throws Exception
	 * @return 返回采购申请的【FID】和【采购订单号】
	 * 
	 * 其他的格式：{"parameters": ["PUR_Requisition","请求的json"]}
	 * 
	 */
	public static Map<String, Object> saveData(ServiceLogBean logBean, Object dataJson, String formid) throws Exception {
		String url = PropUtil.getString("k3.saveData.url");
		Object[] objs = new Object[] {formid, dataJson};
		Map<String, Object> inputMap = handlResMap(formid, dataJson);
		inputMap.put("parameters", objs);
		String inputJson = JsonUtil.toJson(inputMap);
		log.info("inputJson:"+inputJson);
		List<String> cookies = k3Login();
		String resule = HttpRequestUtil.postJson(url, inputMap, cookies);
		ERPResponseResult result = JsonUtil.fromJson(resule, ERPResponseResult.class);
		
		// 保存日志
		String outJson = JsonUtil.toJson(result);
		saveLog(logBean, url+", formid:"+formid, inputJson, outJson); 
		
		boolean bl = result.getResult().getResponseStatus().getIsSuccess();
		if(!bl) {
			throw new RuntimeException("金蝶系统接口返回错误信息："+errorMsg(result));
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer erpFID = result.getResult().getId();
		String erpNumber = result.getResult().getNumber();
		resultMap.put("FID", erpFID);
		resultMap.put("Number", erpNumber);
		return resultMap;
	}
	
	/**
	 * 应付单下推单据接口
	 * @param dataJson 采购DataJson数据
	 * @throws Exception
	 * @return 返回采购申请的【FID】和【采购订单号】
	 * 
	 * 其他的格式：{"parameters": ["PUR_Requisition","请求的json"]}
	 * 
	 */
	public static Map<String, Object> pushData(ServiceLogBean logBean, Object dataJson) throws Exception {
		String url = PropUtil.getString("k3.pushData.url");
		String formid = PropUtil.getString("k3.yfd.formid");
		Map<String, Object> inputMap = handlResMap(formid, dataJson);
		List<String> cookies = k3Login();
		String resule = HttpRequestUtil.postJson(url, inputMap, cookies);
		ERPPPayableResult result = JsonUtil.fromJson(resule, ERPPPayableResult.class);
		
		// 保存日志
		String inputJson = JsonUtil.toJson(inputMap);
		String outJson = JsonUtil.toJson(result);
		saveLog(logBean, url+", formid:"+formid, inputJson, outJson); 
		
		boolean bl = result.getResult().getResponseStatus().getIsSuccess();
		if(!bl) {
			throw new RuntimeException("金蝶系统接口返回错误信息："+errorMsg(result));
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<SuccessEntitys> listSuccess = result.getResult().getResponseStatus().getSuccessEntitys();
		List<String> listNumbers = new ArrayList<String>();
		List<String> listFids = new ArrayList<String>();
		for(SuccessEntitys success : listSuccess) {
			listNumbers.add(success.getNumber());
			listFids.add(success.getId()+"");
		}
		resultMap.put("FID", CustomUtil.join(listFids, ","));
		resultMap.put("Number", CustomUtil.join(listNumbers, ","));
		return resultMap;
	}
	
	public static Map<String, Object> handlResMap(String formid, Object dataJson) {
		Object[] objs = new Object[] {formid, dataJson};
		Map<String, Object> inputMap = new HashMap<String, Object>();
		inputMap.put("parameters", objs);
		log.info("inputJson:"+JsonUtil.toJson(inputMap));
		return inputMap;
	}
	
	/**
	 * K3报错信息
	 * @param result
	 * @return
	 */
	public static String errorMsg(ERPResponseResult result) {
		List<Errors> errors = result.getResult().getResponseStatus().getErrors();
		String errorStr = "";
		for(Errors error : errors) {
			if(CustomUtil.isBlank(errorStr)) {
				errorStr = "FieldName:"+error.getFieldName() + "</br> Message:" + error.getMessage()+"</br>";
			}else {
				errorStr = errorStr + "</br>" + "FieldName:"+error.getFieldName() + "</br> Message:" + error.getMessage()+"</br>";
			}
		}
		return errorStr;
	}
	
	/**
	 * K3报错信息
	 * @param result
	 * @return
	 */
	public static String errorMsg(ERPPPayableResult result) {
		List<PayableErrors> errors = result.getResult().getResponseStatus().getErrors();
		String errorStr = "";
		for(PayableErrors error : errors) {
			if(CustomUtil.isBlank(errorStr)) {
				errorStr = "FieldName:"+error.getFieldName() + "</br> Message:" + error.getMessage()+"</br>";
			}else {
				errorStr = errorStr + "</br>" + "FieldName:"+error.getFieldName() + "</br> Message:" + error.getMessage()+"</br>";
			}
		}
		return errorStr;
	}
	
	private static void saveLog(ServiceLogBean logBean, String url, String inputJson, String outJson) {
		// 日志
		logBean.setUrl(url);
		logBean.setStatus(1);
		logBean.setReqBody(inputJson);	// 请求Json字符串
		logBean.setResBody(outJson);	// 响应JsonJson字符串结果
		logBean.setEndTime(System.currentTimeMillis());
		logBean.setClientIp("");
		logBean.setServerIp(CustomUtil.getLocalIP());
		
		logBean.saveLog(logBean);	// 保存日志
	}
	
	

}
